package com.htfyun.factorytest;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.FileUtils;
import android.os.SystemProperties;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;

import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.common.SettingsUtils;
import com.htfyun.factorytest.config.EinkProperty;
import com.htfyun.factorytest.iflytekWakeup.IflytekSpeechInit;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.ReflectUtils;
import com.htfyun.factorytest.utils.ShellUtils;
import com.htfyun.factorytest.utils.SystemPropertyUtil;
import com.htfyun.factorytest.utils.UsefulUtils;
import com.htfyun.factorytest.utils.executor.AppExecutors;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.io.IOException;

public class RootApplication extends Application {

    public static Context getContext() {
        return mInstance.getApplicationContext();
    }

    private static RootApplication mInstance;

    public static synchronized RootApplication getInstance() {
        return mInstance;
    }

    //    private static Context mContext;
    public static boolean isExistHomeKey = false;
    public static boolean isExistVolumeKey = false;
    public static boolean isExistBackKey = false;
    public static boolean isExistHallKey = false;
    public static boolean isExistDragKey = false;
    public static boolean isExistRefreshKey = false;
    public static boolean isExistSlideKey = false;
    public static boolean isExistPageUpKey = false;
    public static boolean isExistPageDownKey = false;
    public static boolean isExistSearchKey = false;
    public static boolean isExistF2Key = false;

    //    public static boolean isExistETP = false;
    public static boolean hasSIMCard = false;

    public static boolean enableUsbCheck = false;

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        MMKV.initialize(this, getFilesDir().getAbsolutePath() + File.separator + "htfyun");
        //enable abc log
        if (SystemProperties.getInt(Constants.PERSIST_SYS_ABC_SWITCH, 0) != 1) {
            DebugLog.d("setprop persist.sys.abc_switch=1");
            SystemPropertyUtil.setSystemProperty(Constants.PERSIST_SYS_ABC_SWITCH, "1");
        }

        if (0 != SystemProperties.getInt(Constants.PERSIST_EINK_BAR_FLAG, 2)) {
            DebugLog.d("setprop persist.eink.bar.flag=0");
            SystemPropertyUtil.setSystemProperty(Constants.PERSIST_EINK_BAR_FLAG, "0");
        }

        //要获取 SIM 卡状态, 要设置 sys.modem.in_test 为 false;
        if(SystemProperties.getBoolean(Constants.PERSIST_MODEM_IN_TEST, false)){
            DebugLog.d("setprop " + Constants.PERSIST_MODEM_IN_TEST + " to be false");
            SystemPropertyUtil.setSystemProperty(Constants.PERSIST_MODEM_IN_TEST, "0");
        }

        getDeviceHardWareInfo();
        AppExecutors.runOnIoThread(() -> copy(Constants.OEM_COPY, Constants.EXTERNAL_STORAGE));

        IflytekSpeechInit.init(this);

        SettingsUtils.setScreenOffTimeForFT(this);
        try {
            FileUtils.copyToFileOrThrow(getAssets().open("standby.png"), new File(getExternalFilesDir(null).getAbsolutePath() + File.separator + "standby.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*if (FactoryTestItemsEnum.pcba.isPassed(getContext())) {
            AppExecutors.runOnIoThread(() -> {
                Configuration config = Configuration.getInstance();
                config.setConfig(Constants.SECTION_PCBA, Constants.SECTION_PCBA, "1");
                for (FactoryPCBAActivity.PCBATestItemEnum itemsEnum : FactoryPCBAActivity.PCBATestItemEnum.values()) {
                    if (FactoryPCBAActivity.isContinue(DeviceAttr.getRunningDeviceAttr(), itemsEnum)) {
                        continue;
                    }
                    config.setConfig(Constants.SECTION_PCBA, itemsEnum.name(), "1");
                }
            });
        }*/
//        copy(FROM_PATH, TO_PATH);
    }

/*    private void copyJson() {
        File file = new File(Constants.OEM_COPY);
        if (file.exists() && file.list() != null) {
            File[] files = file.listFiles();
            for (File f : files) {
                try {
                    FileUtils.copyFileOrThrow(f, new File(Constants.EXTERNAL_STORAGE + f.getName()));
                    DebugLog.i("copy " + f.getName() + "To /sdcard");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

//    private final static String FROM_PATH = "/data/misc/logd";
//    private final static String TO_PATH = Constants.EXTERNAL_STORAGE + "EXPORT/logd";

    public void copy(String fromFile, String toFile) {
        File root = new File(fromFile);
        if (root.exists() && root.list() != null) {
            File[] files = root.listFiles();
            File targetDir = new File(toFile);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            for (File f : files) {
                try {
                    if (f.isDirectory()) {
                        copy(f.getPath() + File.separator, toFile + File.separator + f.getName());
                        continue;
                    }
                    FileUtils.copyFileOrThrow(f, new File(toFile + File.separator + f.getName()));
                    DebugLog.i("copy " + f.getName() + "to " + toFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

//    public static Context getContext() {
//        return mContext;
//    }

    @SuppressLint("NewApi")
    private void getDeviceHardWareInfo() {

/*        if ("1".equals(SystemPropertyUtil.getSystemProperty(RO_EINK_LIGHT_ENABLED))) {
            hasForeLight = true;
        }

        if ("1".equals(SystemPropertyUtil.getSystemProperty(RO_EINK_CAMERA_ENABLED))) {
            hasCamera = true;
        }

        if ("1".equals(SystemPropertyUtil.getSystemProperty(RO_EINK_FINGERPRINT_ENABLED))) {
            hasFingerprint = true;
        }*/
        if (UsefulUtils.isSupportedMobile()) {
            hasSIMCard = true;
            Log.d(DebugLog.TAG, "has SIMCard");
        }
        /*if (!SystemProperties.getBoolean(Constants.RO_EINK_SIMCARD_ENABLED, true)) {
            hasSIMCard = true;
            if (Constants.RILD_LIBPATH_MEIG.equals(SystemProperties.get(Constants.RILD_LIBPATH_KEY, ""))) {
                enableUsbCheck = true;
                if (!getBoolean(mInstance, Constants.USB_CALIBRATION_MODE, false)) {
                    String s = "echo -en \"AT+SYSNV=1,\\\"diag_device\\\",1\\r\\n\" > /dev/ttyUSB0";
                    DebugLog.i("Disable USB Calibration mode " + ShellUtils.execCommand(s, false).toString());

                    setBoolean(mInstance, Constants.USB_CALIBRATION_MODE, true);
                }
            }
            DebugLog.d("has SIMCard");
        }*/

        InputManager im = (InputManager) getSystemService(INPUT_SERVICE);
        int[] ids = im.getInputDeviceIds();
        for (int id : ids) {
            InputDevice device = im.getInputDevice(id);
            boolean isExternal = (boolean) ReflectUtils.invokeMethodWithNoException(device, "isExternal");
            if (isExternal) {
                DebugLog.d(device.getName());
                continue;
            }

            if ((device.getSources() & InputDevice.SOURCE_KEYBOARD) != 0
                    && (device.getSources() & InputDevice.SOURCE_MOUSE) != 0) {

                boolean[] hasKey = device.hasKeys(KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_VOLUME_UP,
                        KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_SLEEP,
                        Constants.KEYCODE_DRAG, Constants.KEYCODE_REFRESH, Constants.KEYCODE_SLIDE,
                        KeyEvent.KEYCODE_PAGE_UP, KeyEvent.KEYCODE_PAGE_DOWN, KeyEvent.KEYCODE_SEARCH, KeyEvent.KEYCODE_F2);
                if (hasKey[0]) {
                    isExistHomeKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_HOME");
                }
                if (hasKey[1] && hasKey[2]) {
                    isExistVolumeKey = true;
                    DebugLog.d("device: " + device.getName() + " has VolumeKey");
                }
                if (hasKey[3]) {
                    isExistBackKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_BACK");
                }
                if (hasKey[4]) {
                    if (EinkProperty.isAoyi60s()) {
                        return;
                    }
                    isExistHallKey = true;
                    DebugLog.d("device = " + device.getName() + " has KEYCODE_SLEEP");
                }
                if (hasKey[5]) {
                    isExistDragKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_DRAG");
                }
                if (hasKey[6]) {
                    isExistRefreshKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_REFRESH");
                }
                if (hasKey[7]) {
                    isExistSlideKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_SLIDE");
                }
                if (hasKey[8]) {
                    isExistPageUpKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_PAGE_UP");
                }
                if (hasKey[9]) {
                    isExistPageDownKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_PAGE_DOWN");
                }
                if (hasKey[10]) {
                    isExistSearchKey = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_SEARCH");
                }
                if (hasKey[11]) {
                    isExistF2Key = true;
                    DebugLog.d("device: " + device.getName() + "has KEYCODE_F2");
                }

            }

            /*if (device.supportsSource(InputDevice.SOURCE_STYLUS) ||
                    device.supportsSource(InputDevice.SOURCE_BLUETOOTH_STYLUS)) {
                isExistETP = true;
            }*/
        }
//        DebugLog.d("hasETP = " + isExistETP);

    }

    private final static String EINK_SHARED_PREF_NAME = "eink_application_shared_preferences";

    private static boolean getBoolean(Context context, String name, boolean defValue) {
        if (context == null) {
            return false;
        }

/*        SharedPreferences sp = context.getSharedPreferences(EINK_SHARED_PREF_NAME, Context.MODE_PRIVATE);

        return sp.getBoolean(name, defValue);*/

        MMKV kv = MMKV.defaultMMKV();
        return kv.decodeBool(name, defValue);
    }

    private static void setBoolean(Context context, String name, boolean value) {
        if (context == null) {
            return;
        }

/*        SharedPreferences sp = context.getSharedPreferences(EINK_SHARED_PREF_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sp.edit();

        editor.putBoolean(name, value);

        editor.apply();*/

        MMKV kv = MMKV.defaultMMKV();
        kv.encode(name, value);
    }
}
